package com.zcsy.manage.web.suggestion;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CommonConfig;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.complain.ComplaintsInfo;
import com.zcsy.manage.model.complain.ComplaintsReply;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.base.ICommonImgService;
import com.zcsy.manage.service.complain.IComplaintsInfoService;
import com.zcsy.manage.service.complain.IComplaintsReplyService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.mall.IIntegralRecordService;

@Controller
@RequestMapping(value = "complaintsInfo")
public class ComplaintsInfoController {

    @Autowired
    private IComplaintsInfoService infoService;

    @Autowired
    private ICommonImgService commonImgService;

    @Autowired
    private IComplaintsReplyService complaintsReplyService;
    
    @Autowired
    private ICommonConfigService commonConfigService;
    
    @Autowired
    private IIntegralRecordService integralRecordService;
    
    @Autowired
    private IIntegralConfigService IntegralConfigService;
    
    public static final int SIZE = 3; // 每页大小
    public static final int platformType = 1; // 平台回复
    public static final int ownerType    = 2; // 业主评价

    /**
     * @Description 分页获取投诉数据列表
     * @param pNo
     *            页数
     * @param title
     *            标题
     * @param state
     *            状态
     * @param type
     *            类型 0环境管理类,1秩序维护类,2客户服务类, 3设备管理与维修
     * @param complainType
     *            投诉对象:0投诉平台或商家，1投诉物业
     * @param level
     *            危害等级
     * @param beginDate
     *            开始时间
     * @param endDate
     *            结束时间
     * @param req
     *            用户的请求
     * @return 返回查询的结果 String 投诉列表jsp页面
     * @author chenxin
     * @date 2016年7月29日下午2:11:38
     */
    @RequestMapping(value = "infoList", method = RequestMethod.GET)
    public String infoList(Model model, Integer pNo, HttpServletRequest req) {

        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, SIZE);
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        List<ComplaintsInfo> rInfoList = infoService.getAll(user.getId());
        PageInfo<ComplaintsInfo> pageInfo = new PageInfo<ComplaintsInfo>(rInfoList);

        model.addAttribute("complaintsInfo", pageInfo);
        model.addAttribute("currentPage", pNo);
        return "suggestion/main_suggestionList";
    }

    /**
     * @description 保存投诉建议以及业主的回复信息
     * @param complaints  投诉对象
     * @return RequestJson 成功或失败
     * @author chenxin
     * @date 2016年7月29日下午3:23:33
     */
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdate(Model model, String title, String content, Integer suggestionType,
            Integer complainType, String houseId, String contactor, String contactorPhone, Integer level, Integer type,
            @RequestParam(value = "imgArr[]" ,required=false) String[] imgArr, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {
            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            
            ComplaintsInfo complaints = new ComplaintsInfo();
            
            complaints.setOwnerId(user.getId());
            complaints.setId(UniqueNumberUtils.get18UniqueNumber());
            complaints.setCreateTime(DateUtils.getDate());
            complaints.setTitle(title);
            complaints.setComplainType(complainType);
            complaints.setContactorPhone(contactorPhone);
            complaints.setContactor(contactor);
            complaints.setContent(content);
            complaints.setLevel(level);
            complaints.setHouseId(houseId);
            complaints.setType(type);
            complaints.setImgArr(imgArr);
            complaints.setSugesstionType(suggestionType);
            complaints.setState(Constants.STATE_DISABLED);

            infoService.insert(complaints);
            
            if (imgArr != null) {
                List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(complaints.getId(),
                        Constants.IMG_COMPLAIN);

                if (CollectionUtils.isNotEmpty(imgs)) {
                    for (CommonImg commonImg : imgs) {
                        commonImgService.deleteById(commonImg.getId());
                    }
                }
                String[] imgArrs = complaints.getImgArr();
                CommonImg commonImg = new CommonImg();
                for (String item : imgArrs) {
                    commonImg.setId(UniqueNumberUtils.get18UniqueNumber());
                    commonImg.setUrl(item);
                    commonImg.setObjId(complaints.getId());
                    commonImg.setObjType(Constants.IMG_COMPLAIN);
                    commonImgService.insert(commonImg);
                }
            }
            
            /**************************************用户单次投诉、建议或者报修，获得积分10************************************/
            //用户Id
            String userId = user.getId();
            String userAccount = user.getLoginname();
            //根据唯一标识name获取“每日积分上限”的小区配置信息
            CommonConfig commonConfig = commonConfigService.getByName("mall_integral_config");
            //用户当天可加积分之和的上限
            Integer maxValuePerDay = commonConfigService.getIntegralMaxValueOfCell("mall_integral_config");
            //根据唯一标识name获取"投诉建议或报修"可获得的积分值
            Integer integralOfcomplaintAndRepair = IntegralConfigService.getIntegralValue("complaint");
            //获取用户当天积分变动之和
            Integer soFarIntegralSum = integralRecordService.getIntegralOfToday(userId);
           
            // 验证小区配置的积分上限值不为空以及值得有效性
            if (commonConfig != null && maxValuePerDay.toString().matches("[0-9]+")) {
                // 当日积分上限 > 投诉建议获得积分 && 当天的积分变动值之和 <（积分上限-投诉建议获得积分）
                if (maxValuePerDay > integralOfcomplaintAndRepair && soFarIntegralSum < (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralMethod(userAccount, "complaint");
                    result.setSuccess(true);
                    result.setMsg("投诉建议成功获得10个积分！");
                }
                // 用户当日变动的积值之和 == 积分上限
                if(soFarIntegralSum == maxValuePerDay) {
                    result.setMsg("已达今日累加积分上限");
                }
                // 用户当日变动积分值之和 < 积分上限 && 用户当日变动积分值之和 >(积分上限-投诉建议成功获得的积分)
                if(soFarIntegralSum < maxValuePerDay && soFarIntegralSum > (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralWhenToMaxValuePerDay(userAccount, "complaint",maxValuePerDay - soFarIntegralSum);
                    result.setMsg("投诉建议成功获得10个积分！，但是已达今日累积积分上限！");
                }
            }
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }

    /**
     * @description 显示投诉详情页面
     * @param id
     *            投诉单号/投诉id
     * @return 返回详情的jsp路径 String
     * @author chenxin
     * @date 2016年7月29日下午3:35:33
     */
    @RequestMapping(value = "showDetails", method = RequestMethod.GET)
    public String showDetails(Integer pNo, Model model, String id) {
        try {
            if (pNo == null) {
                pNo = Constants.PAGE_NO;
            }
            ComplaintsInfo complaintsInfo = infoService.selectByPrimaryKey(id);
            
            ComplaintsReply reply = new ComplaintsReply();
            //平台回复
            reply.setInfoId(id);
            reply.setReplyType(platformType);
            List<ComplaintsReply> platformReply = complaintsReplyService.selectReplyByReplyType(reply);
           
            // 获取业主投诉图
            List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_COMPLAIN);
            model.addAttribute("imgs", imgs);
            
            model.addAttribute("complaintsInfo", complaintsInfo);
            model.addAttribute("platformReply", platformReply);
        } catch (Exception e) {
        }
        return "suggestion/suggestionDetails";
    }

    /**
     * @description 保存评论
     * @param replys
     * @author chenxin
     * @date 2016年8月4日下午6:08:45
     */
    @RequestMapping(value = "saveReply", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveReply(Model model, ComplaintsReply replys,HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            
            replys.setId(UniqueNumberUtils.get18UniqueNumber());
            replys.setReplyType(ownerType);
            replys.setReplyTime(DateUtils.getDate());
            replys.setReplyAccount(user.getUsername());

            complaintsReplyService.insert(replys);
            
            /**************************************用户单次评论获得积分5************************************/
            //用户Id
            String userId = user.getId();
            String userAccount = user.getLoginname();
            //根据唯一标识name获取“每日积分上限”的小区配置信息
            CommonConfig commonConfig = commonConfigService.getByName("mall_integral_config");
            //用户当天可加积分之和的上限
            Integer maxValuePerDay = commonConfigService.getIntegralMaxValueOfCell("mall_integral_config");
            //根据唯一标识name获取"投诉建议或报修"可获得的积分值
            Integer integralOfcomplaintAndRepair = IntegralConfigService.getIntegralValue("common");
            //获取用户当天积分变动之和
            Integer soFarIntegralSum = integralRecordService.getIntegralOfToday(userId);
           
            // 验证小区配置的积分上限值不为空以及值得有效性
            if (commonConfig != null && maxValuePerDay.toString().matches("[0-9]+")) {
                // 当日积分上限 > 投诉建议获得积分 && 当天的积分变动值之和 <（积分上限-投诉建议获得积分）
                if (maxValuePerDay > integralOfcomplaintAndRepair && soFarIntegralSum < (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    //插入积分变更信息
                    integralRecordService.changeIntegralMethod(userAccount, "common");
                    result.setSuccess(true);
                    result.setMsg("评价成功获得5个积分！");
                }
                // 用户当日变动的积值之和 == 积分上限
                if(soFarIntegralSum == maxValuePerDay) {
                    result.setMsg("已达今日累加积分上限");
                }
                // 用户当日变动积分值之和 < 积分上限 && 用户当日变动积分值之和 >(积分上限-投诉建议成功获得的积分)
                if(soFarIntegralSum < maxValuePerDay && soFarIntegralSum > (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralWhenToMaxValuePerDay(userAccount, "common",maxValuePerDay - soFarIntegralSum);
                    result.setMsg("评价成功获得5个积分！，但是已达今日累积积分上限！");
                }
            }
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }
    
    /**
     * @Description: 删除照片
     * @param imageId 照片id
     * @author huangls 1449700087@qq.com
     * @date 2016年8月16日
     */
    @RequestMapping(value = "deleteImage", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteImage(Model model, String imageId, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {
        	
        	if(imageId != null) {
        		commonImgService.deleteById(imageId);
        		result.setSuccess(true);
                result.setMsg("操作成功！");
        	}
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }

}
